package com.bbm.communitysystem.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.io.IOException;
@Slf4j
//@Component
public class AuthFilter implements Filter , Ordered {

    @Value("${filter.admin}")
    private String filter;

    @Value("${filter.url}")
    private String[] url;

    @Value("${filter.urls}")
    private String[] urls;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        log.info("请求进入过滤器 url: {}", request.getRequestURL());
        String admin = request.getAttribute(filter) + "";
        if (!admin.isEmpty() && checkEQ(request.getServletPath())
                || request.getMethod().equals("OPTIONS")
                || checkContains(request.getServletPath())
        ) {
            request.setAttribute("filter", filter);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public int getOrder() {
        return 10;
    }

    private Boolean checkEQ(String path) {
        for (String s : url) {
            if (s.equals(path)) {
                return true;
            }
        }
        return false;
    }

    private Boolean checkContains(String path) {
        for (String s : urls) {
            if (path.contains(s)) {
                return true;
            }
        }
        return false;
    }


}
